#include "client.h"
int main(int argc,char *argv[])
{ 
    ARGS_CHECK(argc,3);
    int sockfd;
    sockfd=socket(AF_INET,SOCK_STREAM,0);
    ERROR_CHECK(sockfd,-1,"socket");
    printf("sockfd=%d\n",sockfd);
    struct sockaddr_in ser;
    bzero(&ser,sizeof(ser));
    ser.sin_family=AF_INET;
    ser.sin_addr.s_addr=inet_addr(argv[1]);
    ser.sin_port=htons(atoi(argv[2]));
    int ret;
    ret=connect(sockfd,(struct sockaddr*)&ser,sizeof(ser));
    ERROR_CHECK(ret,-1,"connect");
    int dataLen;
    char buf[1024]={0};
    //接收文件名
    recvcycle(sockfd,&dataLen,4);
    recvcycle(sockfd,buf,dataLen);
    //接收文件
    char tmp[1024]={0};
    strncpy(tmp,buf,sizeof(tmp));
    int fd;
    //先创建文件
    for(int i=1;-1==(fd=open(tmp,O_RDWR|O_CREAT|O_EXCL,0666));++i)
    {
        bzero(tmp,sizeof(tmp));
        sprintf(tmp,"%s%d",buf,i);
    }
    //接收文件大小,用于打印进度条
    int i=0;
    char schedule[11]={0};
    off_t fsize,downloadsize=0,lastsize=0,fileslice,slice,size=0;
    recvcycle(sockfd,&dataLen,4);
    recvcycle(sockfd,&fsize,dataLen);
    printf("Size of upcoming file = %ld Bytes\n",fsize);
    fileslice=fsize/10000;
    slice=fsize/10;
    printf("======|----------|\n");
    //打印时间
    struct timeval start,end;
    gettimeofday(&start,NULL);
    while(1)
    {
        //bzero(buf,sizeof(buf));
        ret=recvcycle(sockfd,&dataLen,4);
        if(0==ret&&dataLen>0)
        {
            ret=recvcycle(sockfd,buf,dataLen);
            if(-1==ret)//对方断开recvcycle返回-1
            {
                break;
            }
            write(fd,buf,dataLen);
            //打印百分比
            downloadsize+=dataLen;
            if((downloadsize-lastsize)>fileslice)
            {
                if((downloadsize-size)>slice)
                {
                    *(schedule+i)='-';
                    size=downloadsize;
                    ++i;
                }
                printf("%6.2f%%%s\r",(double)downloadsize/fsize*100,schedule);
                fflush(stdout);
                lastsize=downloadsize;
            }
        }else if(0==ret&&dataLen==0)
        {
            gettimeofday(&end,NULL);
            printf("\r100.00%%%s-|\nRecv done! Time used = %ld seconds.\n",schedule,end.tv_sec-start.tv_sec);
            break;
        }else{
            break;
        }
    }
    return 0;
}
